package kamikaze.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpSession;

import kamikaze.entity.Admin;
import kamikaze.entity.User;
import kamikaze.support.HttpMethod;
import kamikaze.support.MessageView;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;
import kamikaze.support.StringUtil;
import kamikaze.support.UserSession;

@ServiceConfig(path = "login.action", method = HttpMethod.POST)
public class LoginService implements Service {

	private static String USER_QUERY = "select u from User u where u.loginId =:loginId and u.password = :password";
	private static String ADMIN_QURY = "select u from Admin u where u.loginId =:loginId and u.password = :password";

	@Override
	public String serve(ServiceContext ctx) throws Exception {

		EntityManager em = ctx.getEntityManager();

		boolean isAdmin = "admin".equals(ctx.getRequest().getParameter("type"));

		List list = em
				.createQuery(isAdmin ? ADMIN_QURY : USER_QUERY)
				.setParameter("loginId", ctx.getRequest().getParameter("username"))
				.setParameter("password", StringUtil.encrypt(ctx.getRequest().getParameter("password")))
				.getResultList();

		if (list.isEmpty()) {
			throw new ServiceException("login failure");
		}
		Object userOrAdmin = list.get(0);

		if (!isAdmin && ((User) userOrAdmin).isSuspended()) {
			throw new ServiceException("you account is suspended");
		}

		HttpSession session = ctx.getRequest().getSession(true);
		session.setAttribute("user.id", isAdmin ? ((Admin) userOrAdmin).getId() : ((User) userOrAdmin).getId());
		session.setAttribute("user.type", isAdmin ? UserSession.Type.Admin : UserSession.Type.User);
		return MessageView
				.from(ctx)
				.setMessage(
						"welcome back " + (isAdmin ? ((Admin) userOrAdmin).getName() : ((User) userOrAdmin).getName()))
				.setNextURL(isAdmin ? "/service/admin/home" : "/service/user/home")
				.getViewName();

	}
}
